package com.zjitc.backend_shop.service.Impl;
import com.zjitc.backend_shop.mapper.UserMapper;
import com.zjitc.backend_shop.pojo.User;
import com.zjitc.backend_shop.service.UserService;
import com.zjitc.backend_shop.utils.MD5WithSaltUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author 王新瑜
 * @date 2024/12/20 15:27
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User findUser(String username, String password){
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("username",username).andEqualTo("password",password);
        List<User> user = userMapper.selectByExample(example);
        if (user.isEmpty()) {
            return null;
        }
        return user.get(0);
    }

    @Override
    public boolean login(String username, String password) {
        MD5WithSaltUtil md5WithSaltUtil = new MD5WithSaltUtil();
        String encryptWithFixedSalt = md5WithSaltUtil.encryptWithFixedSalt(password);
        User user = findUser(username,encryptWithFixedSalt);
        if (user != null) {
            return true;
        }
        return false;
    }

    @Override
    public boolean addUser(User user) {
        MD5WithSaltUtil md5WithSaltUtil = new MD5WithSaltUtil();
        String encryptWithFixedSalt = md5WithSaltUtil.encryptWithFixedSalt(user.getPassword());
        user.setPassword(encryptWithFixedSalt);
        return userMapper.insert(user) > 0;
    }

    @Override
    public User findByUsername(String username) {
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("username", username);
        List<User> users = userMapper.selectByExample(example);
        if (users.isEmpty()) {
            return null;
        }
        return users.get(0);
    }

    @Override
    public List<User> findAllUser() {
        return userMapper.selectAll();
    }
}
